<template>
	<view class="content">
		<view class="padding flex justify-between">
			<view class="left-bgt padding-lr padding-tb-xs margin-right" @click="handleCallPhone">
				如有疑惑，点击联系我们
			</view>
			<view class="right-bgt padding-lr padding-tb-xs" @click="openPop">
				查询之前订单
			</view>
		</view>
		<uv-form labelPosition="left" labelWidth="80" :model="formData"
			:labelStyle="{color: '#999999', 'font-weight': '600'}" :rules="rules" ref="form">
			<view class="bg-white padding-lr">
				<uv-form-item :label="formData.homeworkType == 1?'作物种类':'货物类型'" prop="cropName" borderBottom
					:required="true" :customStyle="customStyle">
					<view class="zwzl-box">
						<view class="zwzl-item" :class="{selected: formData.cropType==item.value}"
							v-for="item in actions" :key="item.value" @click="typeConfirm(item)">
							{{item.label}}
						</view>
					</view>
				</uv-form-item>
				<uv-form-item v-if="formData.homeworkType==2" label="吊运重量" prop="area" borderBottom :required="true"
					:customStyle="customStyle">
					<uv-input placeholder="请估计您所需吊运的货物重量" type="digit" v-model="formData.area" border="none"
						@input="onInputChange">
					</uv-input>
					<template v-slot:right>
						<text>吨</text>
					</template>
				</uv-form-item>
				<template v-else>
					<uv-form-item label="面积" prop="area" borderBottom :required="true" :customStyle="customStyle">
						<uv-input placeholder="请估计您的种植亩数" type="digit" v-model="formData.area" border="none"
							@input="onInputChange">
						</uv-input>
						<template v-slot:right>
							<text>亩</text>
						</template>
					</uv-form-item>
					<uv-form-item label="用水量" prop="cropAcreUsage" borderBottom :required="true"
						:customStyle="customStyle">
						<uv-input type="digit" v-model="formData.cropAcreUsage" @input="onInputChange1">
						</uv-input>
						<template v-slot:right>
							<text class="margin-left-sm">升/亩</text>
							<text class="margin-left color-green">系统自动推荐最佳用水量</text>
						</template>
					</uv-form-item>
				</template>
				<uv-form-item label="作业时间" prop="dockingPeopleTime" borderBottom :required="true"
					:customStyle="customStyle">
					<view class="zwzl-box">
						<view class="zwzl-item cl-gr" :class="{selected: isToday&&formData.dockingPeopleTime}" @click="selectToday">
							今天
						</view>
						<template v-if="isToday || !formData.dockingPeopleTime">
							<view class="zwzl-item cl-gr" @click="openTime">
								其他时间
							</view>
						</template>
						<view v-else>
							{{formData.dockingPeopleTime}}
						</view>
					</view>
					<template v-slot:right>
						<uv-icon name="clock-fill"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="手机号码" prop="regionPhone" borderBottom :required="true" :customStyle="customStyle">
					<uv-input placeholder="飞手会通过该号码联系您 " v-model="formData.regionPhone" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="作业地址" prop="address" borderBottom :required="true" :customStyle="customStyle">
					<!-- <uv-input v-model="formData.address" disabled disabledColor="#ffffff" border="none">
					</uv-input> -->
					<view class="" v-if="formData.address">
						{{formData.address}}
					</view>
					<button v-else class="cu-btn bg-blue" style="width: 250rpx;" @click="autoAddress">点击自动定位</button>
					<template v-slot:right>
						<uv-icon name="map-fill" @click="chooseLocation"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="详细地址" prop="detailAddress" borderBottom :customStyle="customStyle">
					<uv-textarea :maxlength="-1" autoHeight v-model="formData.detailAddress" border="none">
					</uv-textarea>
				</uv-form-item>
				<uv-form-item label="备注" prop="remarks" borderBottom :customStyle="customStyle">
					<uv-textarea :maxlength="-1" autoHeight v-model="formData.remarks" border="none">
					</uv-textarea>
				</uv-form-item>
			</view>

		</uv-form>

		<uv-datetime-picker ref="datetimePicker" :minDate="minDate" :maxDate="1786778555000" v-model="dateValue"
			mode="datetime" @confirm="confirmTime">
		</uv-datetime-picker>

		<view class="foot-box">
			<view class="flex align-center justify-between solid-bottom padding-sm">
				<view class="">
					<text>单价</text>
					<text
						class="color-red text-lg text-bold">￥{{formData.price||'-'}}/{{formData.homeworkType==1?'亩':'吨'}}</text>
				</view>
				<view class="">
					<text>起步价</text>
					<text class="color-red text-lg text-bold">￥{{formData.startingPrice||'-'}}</text>
				</view>
				<view class="">
					<view class="flex align-center" @click="showModal">
						<uv-icon name="question-circle-fill" color="#0BCA89" size="20"></uv-icon>
						价格说明
					</view>
					<!-- <text class="color-red text-lg text-bold">￥{{formData.discountAmount|| '-'}}</text> -->
				</view>
			</view>
			<view class="flex align-center justify-between padding-sm">
				<view class="margin-left margin-right-lg">
					<view class="text-black text-sm text-center">
						预估总价
					</view>
					<view class="color-red text-center">
						<text class="text-lg text-bold">{{formData.money || '-'}}</text>
						<text class="text-sm">元</text>
						<text class="reduce-m text-gray"
							v-if="formData.totalAmount>formData.money">￥{{formData.totalAmount || '-'}}</text>
					</view>
				</view>
				<button class="cu-btn bg-green flex-sub" @click="submit">提交</button>
			</view>
		</view>

		<HistoryPopup ref="historyPopup" @selected="onSelected" />
		<MapPopup ref="mapPopup" @selectedAddr="addrBack" />
		<PriceDetailModal ref="priceDetailModal" />
	</view>
</template>
<script>
	import HistoryPopup from './HistoryPopup.vue'
	import PriceDetailModal from "@/components/priceDetailModal/index"
	import {
		selectDictLabel
	} from '@/utils/huida.js'
	import MapPopup from './MapPopup.vue'
	export default {
		// dicts: ["homework_type"],
		components: {
			HistoryPopup,
			MapPopup,
			PriceDetailModal
		},
		data() {
			return {
				isToday: true,
				customStyle: {
					padding: '15px 0'
				},
				minDate: Date.now(),
				addName: '',
				formData: {
					"orderName": "",
					"regionContact": "",
					"regionPhone": "",
					"cropType": "",
					"cropName": "",
					"homeworkType": "",
					"homeworkTypeName": "",
					"money": 0,
					"totalAmount": 0,
					"price": "",
					"startingPrice": "",
					"acreUsage": "",
					"discountAmount": "",
					"address": "",
					"detailAddress": "",
					"area": "",
					"cropAcreUsage": "",
					"drugRequire": "",
					"homeworkStartTime": "",
					"dockingPeopleTime": "",
					"lng": "",
					"lat": ""
				},
				dateValue: Number(new Date()),
				actionsHw: [],
				actions: [],
				rules: {
					'orderName': {
						type: 'string',
						required: true,
						message: '请输入订单任务',
						trigger: ['blur', 'change']
					},
					'regionContact': {
						type: 'string',
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					'regionPhone': {
						type: 'string',
						required: true,
						message: '请输入手机号码',
						trigger: ['blur', 'change']
					},
					'area': {
						type: 'string',
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					},
					'homeworkTypeName': {
						type: 'string',
						required: true,
						message: '请选择作业类型',
						trigger: ['blur', 'change']
					},
					'dockingPeopleTime': {
						type: 'string',
						required: true,
						message: '请选择作业时间',
						trigger: ['blur', 'change']
					},
					'cropAcreUsage': {
						type: 'string',
						required: true,
						message: '请输入亩用量',
						trigger: ['blur', 'change']
					},
					'cropName': {
						type: 'string',
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					},
					address: {
						type: 'string',
						required: true,
						message: '请选择地址',
						trigger: ['blur', 'change']
					}
				},
				id: '',
				orderLogId: '',
				allowCity:[]
			}
		},
		onLoad(data) {
    		const storedFormData = uni.getStorageSync('formData');

			 if (storedFormData) {
				this.formData = storedFormData;
				uni.removeStorageSync('formData');
				console.log('1111:', this.formData);
			} else {
				this.formData.homeworkType = data.homeworkType;
			}

			// 刚进来的作业时间是今天
			this.formData.dockingPeopleTime = uni.$uv.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
			if (this.formData.homeworkType == 1) {
				uni.$uv.http.get('/cadre/highSeasOrder/cropType').then(res => {
					this.actions = res.data.map(item => ({
						name: item.dictLabel,
						label: item.dictLabel,
						value: item.dictValue
					}))
				})
			} else {
				uni.$uv.http.get('/system/dict/data/type/lifting_type').then(res => {
					this.actions = res.data.map(item => ({
						name: item.dictLabel,
						label: item.dictLabel,
						value: item.dictValue
					}))
				})
			}
			const user = uni.getStorageSync('userInfo')
			this.formData.regionContact = user.name
			this.formData.regionPhone = user.contact
			this.id = data.id
			this.orderLogId = data.orderLogId

			uni.$uv.http.get('/system/dict/data/type/homework_type').then(res => {
				this.actionsHw = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
				this.formData.homeworkTypeName = selectDictLabel(this.actionsHw, data.homeworkType)
			})
			if (data.id) {
				this.fetchDetail()
			}
		},
		methods: {
			handleCallPhone() {
				uni.showLoading()
				this.$http.get('/system/config/phone').then(res => {
					uni.hideLoading()
					if (res.code == 200 && res.data.configValue) {
						uni.makePhoneCall({
							phoneNumber: res.data.configValue, // 电话号码
							success: function() {
								console.log('拨打电话成功');
							},
							fail: function() {
								console.log('拨打电话失败');
							}
						});
					} else {
						uni.showToast({
							icon: 'error',
							title: '暂时无法拨通'
						})
					}
				})
			},
			// 价格说明
			showModal() {
				if (!this.formData.cropType) return uni.showToast({
					title: this.formData.homeworkType == 1 ? '请选择作物种类' : '请选择货物类型',
					icon: 'none'
				})
				if (!this.formData.area) return uni.showToast({
					title: this.formData.homeworkType == 1 ? '请输入作业面积' : '请输入吊运重量',
					icon: 'none'
				})
				if (this.formData.homeworkType == 1 && !this.formData.cropAcreUsage) return uni.showToast({
					title: '请输入亩用量',
					icon: 'none'
				})
				this.$refs.priceDetailModal.show({
					cropType: this.formData.cropType,
					area: this.formData.area,
					cropAcreUsage: this.formData.cropAcreUsage,
					homeworkType: this.formData.homeworkType,
					homeworkTypeName: this.formData.homeworkTypeName
				})
			},
			// 查询之前订单
			openPop() {
				this.$refs.historyPopup.open(this.formData.homeworkType)
			},
			goBack() {
				uni.navigateBack()
			},
			// 详情
			fetchDetail() {
				this.$http.get(`/cadre/assignOrder/getDatail`, {
					params: {
						id: this.id,
						...(this.$hd.position || {}),
					}
				}).then(res => {
					// res.data.cropName = selectDictLabel(this.actions, res.data.cropType)
					res.data.homeworkTypeName = selectDictLabel(this.actionsHw, res.data.homeworkType)
					if (res.data.orderName.indexOf(res.data.cropName) != -1) {
						const arr = res.data.orderName.split(res.data.cropName)
						this.addName = arr[0]
					} else {
						this.addName = ''
					}
					this.formData = res.data
				})
			},
			// 暂存
			submitPre() {
				this.formData.isTemporarily = 1;
				const payload = {
					orderId: this.id,
					orderLogId: this.orderLogId,
					...this.formData,
					status: 4
				}
				this.$http.post('/cadre/orderException/add', payload)
					.then(res => {
						uni.showToast({
							icon: 'success',
							title: '暂存成功',
							duration: 1500,
							complete: () => {
								const pages = getCurrentPages();
								if (pages.length > 1) {
									uni.navigateBack();
								} else {
									uni.reLaunch({
										url: '/subPages\pages\exceptionList\index'
									});
									uni.navigateBack();
								}
							}
						})
					})
			},
			// 提交
			submit() {
				const user = uni.getStorageSync('userInfo')
				if (!user) {
					const storedFormData = uni.getStorageSync('formData');
					if (storedFormData) {
						// 如果存在旧数据，先移除
						uni.removeStorageSync('formData');
					}

					// 没登录的话先保存表单数据
					this.formData.homeworkType = Number(this.formData.homeworkType);
					uni.setStorageSync('formData', this.formData); // 保存新的 formData
					console.log('formData111', this.formData);

					uni.$uv.route("/pages/public/login");
					return;
				}

				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {
					this.formData.orderName = this.addName + this.formData.cropName + this.formData
						.homeworkTypeName + this.formData.area
					if (this.formData.homeworkType == 1) {
						this.formData.orderName += '亩'
					} else {
						this.formData.orderName += '吨'
					}
					let url = '/cadre/highSeasOrder/add'
					if (this.id) {
						url = '/cadre/highSeasOrder/edit'
					}
					this.$http.post(url, this.formData).then(res => {
						uni.showToast({
							icon: res.code === 200 ? 'success' : 'error',
							title: res.msg || '未知返回'
						})
						if (res.code === 200) {
						const pages = getCurrentPages();
						if (pages.length > 1) {
							uni.navigateBack();
						} else {
							uni.reLaunch({
							url: '/pages/index/index',
							});
						}
						}
					}).catch(err => {
						const msg =
							(err.response && err.response.data && err.response.data.msg) ||
							(err.data && err.data.msg) ||
							err.message ||
							'网络错误'
						uni.showToast({
							icon: 'error',
							title: msg
						})
					})
				}).catch(errors => {
					uni.showToast({
						icon: 'none',
						title: '请检查输入项是否完整'
					})
				})
			},
			// 重置
			reset() {
				this.$refs.form.resetFields();
				this.$refs.form.clearValidate();
			},
			openTime() {
				this.$refs.datetimePicker.open();
			},
			confirmTime(e) {
				this.isToday = false
				this.formData.dockingPeopleTime = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				this.$refs.form.validateField('dockingPeopleTime')
			},
			selectToday() {
				this.isToday = true
				this.formData.dockingPeopleTime = uni.$uv.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
				this.$refs.form.validateField('dockingPeopleTime')
			},
			// 类型选择返回结果
			typeConfirm(e) {
				this.formData.cropType = e.value
				this.formData.cropName = e.name
				this.fetchMoney()
			},
			reloadData() {
				this.formData.money = 0
				this.formData.area = ''
				this.formData.cropName = ''
				this.formData.cropType = ''
				this.formData.totalAmount = 0
				this.formData.price = ''
				this.formData.startingPrice = ''
				this.formData.acreUsage = ''
				this.formData.cropAcreUsage = ''
				this.formData.discountAmount = ''
				this.formData.drugRequire = ''
			},
			// 自动获取地址
			autoAddress() {
				this.$refs.mapPopup.open({
					// address:this.formData.address,
					lat: this.formData.lat || this.$hd.position?.lat || 22.83393,
					lng: this.formData.lng || this.$hd.position?.lng || 108.31343 //,
				})
				// 判断是否在开放地区
				// if (this.allowCity) {
				// 	const city = this.$hd.position?.city
				// 	if (this.allowCity.indexOf(city) == -1) {
				// 		return uni.showToast({
				// 			title: '当前地区暂未开放，请打开地图选择！',
				// 			icon: 'none'
				// 		})
				// 	}
				// }
				// this.formData.lat = this.$hd.position?.lat
				// this.formData.lng = this.$hd.position?.lng
				// this.formData.address = this.$hd.position?.addr
				// this.addName = this.$hd.position?.city + this.$hd.position?.district
			},
			// 打开地址
			chooseLocation() {
				this.$refs.mapPopup.open({
					// address:this.formData.address,
					lat: this.formData.lat || this.$hd.position?.lat || 22.83393,
					lng: this.formData.lng || this.$hd.position?.lng || 108.31343 //,
				})
			},
			onInputChange() {
				this.fetchMoney()
			},
			onInputChange1(e) {
				if (!this.formData.area || !e) return
				this.fetchMoney(e)
			},
			// 获取金额
			fetchMoney(v) {
				if (this.formData.homeworkType == 1 && (!this.formData.cropType || !this.formData.area)) return
				if (this.formData.homeworkType == 2 && !this.formData.area) return
				const fn = () => {
					this.$http.get('/cadre/highSeasOrder/sumAmount', {
						params: {
							orderType: 1,
							homeworkType: this.formData.homeworkType,
							cropType: this.formData.cropType,
							cropName: this.formData.cropName,
							area: this.formData.area,
							cropAcreUsage: v
						}
					}).then(res => {
						// console.log('获取金额', res)
						if (res.code != 200) return
						if (this.formData.homeworkType == 2) {
							this.formData.money = res.data.estimatedAmount
							this.formData.startingPrice = res.data.startingPrice || 0
							this.formData.price = res.data.price || 0
						} else {
							this.formData.totalAmount = res.data.totalAmount || 0
							this.formData.price = res.data.price || 0
							this.formData.startingPrice = res.data.startingPrice || 0
							this.formData.acreUsage = res.data.acreUsage || 0
							this.formData.cropAcreUsage = res.data.acreUsage || 0
							this.formData.discountAmount = res.data.discountAmount || 0
							if (res.data.estimatedAmount * 1 < res.data.startingPrice * 1) {
								this.formData.money = res.data.startingPrice
							} else {
								this.formData.money = res.data.estimatedAmount
							}
							// this.formData.money = res.data.estimatedAmount - this.formData.discountAmount
						}
					})
				}
				uni.$uv.debounce(fn, 500)
			},
			// 选择了订单
			onSelected(item) {
				this.isToday = false
				// console.log(item)
				// this.formData.orderName = item.orderName
				this.formData.regionContact = item.regionContact
				this.formData.regionPhone = item.regionPhone
				this.formData.cropType = item.cropType
				this.formData.money = item.money
				this.formData.address = item.address
				this.formData.detailAddress = item.detailAddress
				this.formData.area = item.area
				this.formData.cropAcreUsage = item.cropAcreUsage
				this.formData.drugRequire = item.drugRequire
				this.formData.dockingPeopleTime = ''
				this.formData.lng = item.lng
				this.formData.lat = item.lat
				this.formData.homeworkType = item.homeworkType
				this.formData.homeworkTypeName = selectDictLabel(this.actionsHw, item.homeworkType)

				this.formData.cropName = item.cropName || selectDictLabel(this.actions, item.cropType)

				if (item.orderName.indexOf(this.formData.cropName) != -1) {
					const arr = item.orderName.split(this.formData.cropName)
					this.addName = arr[0]
				} else {
					this.addName = ''
				}
				this.fetchMoney()
			},
			addrBack(item) {
				this.formData.address = item.address
				this.formData.lng = item.location.lng
				this.formData.lat = item.location.lat
				this.addName = item.city + item.district
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding-bottom: 120px;
	}

	.left-bgt {
		font-weight: 500;
		font-size: 28rpx;
		color: #FEFEFE;
		background-image: url($imagesBasUrl+'/bg-xdleft.png');
		background-size: 100% 100%;
		animation-iteration-count: infinite;
		animation-name: ctanm;
		animation-duration: 2s;
		// animation-delay: 5s;
	}

	.right-bgt {
		font-weight: 500;
		font-size: 28rpx;
		color: #FEFEFE;
		background-image: url($imagesBasUrl+'/bg-xdright.png');
		background-size: 100% 100%;
	}

	.foot-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		// display: flex;
		// align-items: center;
		// justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
	}

	.color-red {
		color: #FE3A6A;
	}

	.reduce-m {
		text-decoration-line: line-through;
	}

	@keyframes ctanm {
		0% {
			transform: scale3d(1, 1, 1);
		}

		50% {
			transform: scale3d(1.05, 1.05, 1.05);
		}

		100% {
			transform: scale3d(1, 1, 1);
		}
	}

	.zwzl-box {
		display: flex;
		flex-wrap: wrap;
		align-items: center;

		.zwzl-item {
			min-width: 168rpx;
			text-align: center;
			margin-right: 10rpx;
			margin-bottom: 10rpx;
			background: #DFFAF1;
			border-radius: 10rpx;
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
			padding: 10rpx 20rpx;
		}

		.cl-gr {
			color: #A7A7B5;
		}

		.selected {
			color: #fff;
			background: #0BCA89;
			background-image: url($imagesBasUrl+'/icon-gou.png');
			background-size: 32rpx 32rpx;
			background-position: right bottom;
			background-repeat: no-repeat;
			border: 1px solid #0BCA89;
		}

	}
</style>